package com.zhuang.springbootnio.thread;

import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;

public class OrderService {

    // 提交订单
    public void submitOrder(Order order) {
        // 1. 保存订单到数据库（同步操作）
        saveOrderToDatabase(order);

        // 2. 使用CompletableFuture并行执行多个异步任务
        CompletableFuture<Void> emailFuture = CompletableFuture.runAsync(
                () -> sendOrderConfirmationEmail(order),
                ThreadPoolConfig.ioThreadPool
        );

        CompletableFuture<Void> inventoryFuture = CompletableFuture.runAsync(
                () -> updateInventory(order),
                ThreadPoolConfig.ioThreadPool
        );

        CompletableFuture<Void> logFuture = CompletableFuture.runAsync(
                () -> recordOrderLog(order),
                ThreadPoolConfig.ioThreadPool
        );

        CompletableFuture<Void> pointsFuture = CompletableFuture.runAsync(
                () -> calculatePoints(order),
                ThreadPoolConfig.cpuThreadPool
        );

        CompletableFuture<Void> marketingFuture = CompletableFuture.runAsync(
                () -> sendMarketingPush(order),
                ThreadPoolConfig.ioThreadPool
        );

        // 3. 等待所有异步任务完成
        try {
            CompletableFuture.allOf(
                    emailFuture, inventoryFuture, logFuture, pointsFuture, marketingFuture
            ).exceptionally(ex -> {
                // 处理异常
                System.err.println("订单异步处理失败: " + ex.getMessage());
                return null;
            }).get(); // 阻塞等待所有任务完成
            System.out.println("订单[" + order.getOrderId() + "]处理完成");
        } catch (InterruptedException | ExecutionException e) {
            Thread.currentThread().interrupt();
            System.err.println("订单处理中断: " + e.getMessage());
        }
    }

    // 保存订单到数据库
    private void saveOrderToDatabase(Order order) {
        // 数据库操作...
        System.out.println("保存订单到数据库: " + order.getOrderId());
    }

    // 发送订单确认邮件
    private void sendOrderConfirmationEmail(Order order) {
        // 模拟IO操作
        System.out.println("发送订单确认邮件: " + order.getOrderId());
        try {
            Thread.sleep(500); // 模拟邮件发送延迟
        } catch (InterruptedException e) {
            Thread.currentThread().interrupt();
        }
    }

    // 更新库存
    private void updateInventory(Order order) {
        // 模拟IO操作
        System.out.println("更新库存: " + order.getOrderId());
        try {
            Thread.sleep(300); // 模拟库存更新延迟
        } catch (InterruptedException e) {
            Thread.currentThread().interrupt();
        }
    }

    // 记录订单日志
    private void recordOrderLog(Order order) {
        // 模拟IO操作
        System.out.println("记录订单日志: " + order.getOrderId());
        try {
            Thread.sleep(200); // 模拟日志记录延迟
        } catch (InterruptedException e) {
            Thread.currentThread().interrupt();
        }
    }

    // 计算用户积分
    private void calculatePoints(Order order) {
        // 模拟CPU密集型操作
        System.out.println("计算用户积分: " + order.getOrderId());
        for (int i = 0; i < 1000000; i++) {
            // 模拟复杂计算
        }
    }

    // 发送营销推送
    private void sendMarketingPush(Order order) {
        // 模拟IO操作
        System.out.println("发送营销推送: " + order.getOrderId());
        try {
            Thread.sleep(400); // 模拟推送延迟
        } catch (InterruptedException e) {
            Thread.currentThread().interrupt();
        }
    }
}

